package com.book.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.book.dao.BookDao;
import com.book.dao.CartDao;
import com.book.domain.Book;
import com.book.domain.Product;
import com.book.domain.User;

/**
 * Servlet implementation class CartServlet
 */
public class CartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CartServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		User user = (User) request.getSession().getAttribute("user");
		if (user == null) {
		    StringBuffer beforeloginurl=	request.getRequestURL();
		    beforeloginurl.append("?");
		    beforeloginurl.append(request.getQueryString());
		    
		    
		    System.out.println("query string======"+request.getQueryString());
		    request.getSession().setAttribute("beforeloginurl", beforeloginurl);
			request.getRequestDispatcher("/page/front/login.jsp").forward(
					request, response);
		} else {
			int id = Integer.parseInt(request.getParameter("id"));
			CartDao cartDao=new CartDao();
			Product product=new Product();
			product.setProductid(id);
			BookDao bookDao=new BookDao();
			Book book=new Book();
			book.setId(id);
		    Book book2=	bookDao.selectBook(book);
			product.setBookname(book2.getBookname());
			product.setBookcount(1);
			product.setBookprice(book2.getBookprice());
			product.setBooksprice(1*book2.getBookprice());
			product.setUserid(user.getId());
			cartDao.addProduct(product);
			System.out.println("插入购物车成功");
		    List<Product> products=	cartDao.getAllProducts(user);
			request.setAttribute("products", products);
			request.getRequestDispatcher("/page/front/cart.jsp").forward(request, response);
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}

}
